import {
	service
} from "@/api/http"
// import { setUserinfo } from "../userinfo/userinfo"

export const getToken = () => {
	try {
		const data = uni.getStorageSync('token')
		if (Date.now() >= data.expires) {
			return ""
		} else {
			return data.access_token
		}
	} catch (e) {
		// uni.showToast({
		// 	title: '登录过期，请重新登录！',
		// 	icon: "none"
		// })
		return ""
	}
}
export const setToken = (token) => {
	try {
		uni.setStorageSync('token', token)
	} catch (e) {
		// uni.showToast({
		// 	title: '登录失败，请重新登录！',
		// 	icon: "none"
		// })
	}
}
export const clearToken = () => {
	try {
		uni.removeStorageSync('token')
	} catch (e) {
		// Do something when catch error
	}
}
/**
 * 跳转登录
 */
export const jumpLogin = () => {
	uni.showModal({
		title: '温馨提示',
		content: '您还未登录，当前页面无法访问！',
		confirmText: "去登录",
		complete: (res) => {
			if (res.cancel) {
				uni.navigateBack()
			}
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/login/wechat/wechat',
				})
			}
		}
	})
	uni.navigateTo({
		url: '/subpackage/pages/login',
	})
	return true
}


/**
 * 判断token是否过期
 */
export const isTokenValid = () => {
	const token = getToken()
	return new Promise((resolve, reject) => {
		if (token) {
			uni.request({
				url: service.baseUrl + '/userApi/auth/userInfo',
				method: "GET",
				header: {
					Authorization: 'Bearer ' + token?.accessToken,
					'X-Authorization': 'Bearer ' + token?.refreshToken,
				},
				success: ({
					data
				}) => {
					if (data.code == 200) {
						resolve({
							valid: true,
							data: data.result
						});
					} else {
						uni.clearStorage()
						reject({
							valid: false,
							data: {}
						});
					}
				}
			})
		} else {
			reject({
				valid: false,
				data: {}
			});
		}
	});
}


export const getApiToken = () => {
	uni.request({
		method: "GET",
		url: "https://8f242f0a44ae45e58ff8e557244c0ea3:f1c8a655394844d68dfb6db1e76db040@open.libsp.cn/oauth/token?grant_type=client_credentials&scope=x",
		success: ({
			data
		}) => {
			setToken({
				access_token: data.access_token,
				expires: Date.now() + data.expires_in * 1000
			})
		}
	})
}